package book;

import constant.Constant;
import utils.AnalyzingBook;
import utils.ScannerSingleton;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

public class Library {
    //从文件中读取数据 至图书数组 存储书籍
    private Book[] books;
    //记录当前图书馆 实际存书数量
    private int bookCount;
    //下载数据时 需要用到下载工具
    //上传数据时 也需要用到上传工具

    private static Library library;
    private Scanner scanner = null;

    private final AnalyzingBook analyzingBook = new AnalyzingBook();
    private Library() {
        //当调用该构造方法时，要加载文件当中的数据，存储到 books数组 当中
        loadAllbook();
        scanner = ScannerSingleton.getScanner();
    }

    public static Library getLibrary() {
         if (library == null) {
             library = new Library();
         }
        return library;
    }

    public int getBookCount() {
        return bookCount;
    }

    //写成一个独立的方法 后期 实时可以更新 查看 我们当前书架到底有多少本书
    private void loadAllbook() {
        try {
            Book[] allBook = analyzingBook.loadObject(Constant.All_BOOK_FILE_NAME);
            books = new Book[Constant.CAPACITY];
            if (allBook == null) {
                bookCount = 0;
            }else {
                int allBookLen = allBook.length;
                if (allBookLen > books.length) {
                    books = new Book[allBookLen];
                }
                for (int i = 0; i < allBookLen; i++) {
                    books[i] = allBook[i];
                }
                bookCount = allBookLen;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //将图书数据上传至文件中
    private void storeBook() {
        try {
            analyzingBook.storeObject(books,Constant.All_BOOK_FILE_NAME);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //共用的方法
    public void searchBook() {
        System.out.println("查找图书");
        scanner.nextLine();
        System.out.println("请输入你要查找的图书名称：");
        String title = scanner.nextLine();
        Book book = search(title);
        if (book == null) {
            System.out.println("没有你要找的这本书，你查找的书名为：" + title);
        }else {
            System.out.println("你要查找的书籍的详细信息如下：");
            System.out.println(book);
        }
    }
    private Book search(String title) {
        loadAllbook();
        for (int i = 0; i < getBookCount(); i++) {
            Book book = books[i];
            if (book.getTitle().equals(title)) {
                return book;
            }
        }
        return null;
    }
    public void displayBooks() {
        System.out.println("显示图书");
        for (int i = 0;i < bookCount; i++) {
            System.out.println(books[i]);
        }
    }
    public void exist() {
        System.out.println("退出系统");
        System.exit(0);
    }


    public void addBook(Book book) {
        System.out.println("Library类addBook方法执行了......");
        if (bookCount >= books.length) {
            System.out.println("图书馆已满，无法上架更多图书！");
            return;
        }
        if (bookCount == 0) {
            book.setBookID(1);
        }else {
            //自动设置 bookID
            book.setBookID(books[bookCount - 1].getBookID() + 1);
        }
        books[bookCount++] = book;
        storeBook();
        System.out.println("图书 " + book.getTitle() + " 上架成功！");
    }

    public Book searchBookByID(int bookID) {
        loadAllbook();
        for (int i = 0; i < bookCount; i++) {
            Book temporaryBook = books[i];
            if(temporaryBook.getBookID() == bookID) {
                return temporaryBook;
            }
        }
        return null;
    }

    private int searchIndexByID(int bookID) {
        loadAllbook();
        for (int i = 0; i < getBookCount(); i++) {
            Book temporaryBook = books[i];
            if (temporaryBook.getBookID() == bookID) {
                return i;
            }
        }
        return -1;
    }

    public void updateBook(Book book) {
        int index = searchIndexByID(book.getBookID());
        if (index == -1) {
            System.out.println("没有你要更新的图书！");
            return;
        }
        //覆盖当前数组下标的图书信息
        books[index] = book;
        //保存至文件中
        storeBook();
        System.out.println("书籍已被更新，已保存至文件，更新后的书籍为：");
        System.out.println(books[index]);
    }

    public void removeBook(int bookID) {
        int index = searchIndexByID(bookID);
        if (index == -1) {
            System.out.println("没有你要删除的图书！");
            return;
        }
        for (int i = index; i < bookCount - 1; i++) {
            books[i] = books[i + 1];
        }
        books[bookCount - 1] = null;
        storeBook();
        bookCount--;
    }

    public void borrowCount() {
        loadAllbook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            System.out.println("书名：" + book.getTitle() + " 借阅次数：" + book.getBorrowedCount());
        }
    }

    public void generateBook(int n) {
        //加载已有的全部图书
        loadAllbook();
        //把所有书籍放入 临时数组 进行排序
        Book[] tmp = new Book[getBookCount()];
        for (int i = 0; i < getBookCount(); i++) {
            tmp[i] = books[i];
        }
        //开始排序
        Arrays.sort(tmp);
        //把前n本书拷贝到新数组
        Book[] generateBooks = new Book[n];
        for (int i = 0; i < n; i++) {
            generateBooks[i] = tmp[i];
        }
        //打印数组
        System.out.println("最受欢迎的前" + n +"本书籍如下：");
        for (int i = 0;i < generateBooks.length; i++) {
            Book book = generateBooks[i];
            System.out.println("排名：" + (i+1) + " 书名：" + book.getTitle() + " 作者：" + book.getAuthor() + " 借阅次数：" + book.getBorrowedCount());
        }
    }

    public void checkInventory() {
        loadAllbook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            String status = "未借出";
            if (book.isBorrowed()) {
                status = "已借出";
            }
            System.out.println("书籍：" + book.getTitle() + " 借阅状态：" +status);

        }
    }

    public void checkAndRemoveOldBook() {
        loadAllbook();
        //获取当前时间戳
        long currentTimestamp = System.currentTimeMillis();
        //将当前时间戳转换为 LoacalDate
        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp).atZone(ZoneId.systemDefault()).toLocalDate();
        boolean flg = false;
        for (int i = 0;i < getBookCount(); i++) {
            Book book = books[i];
            //获取当前书籍的上架时间
            LocalDate specifiedDate = book.getShelfDate();
            //计算两个日期之间的差值（以年为单位）
            long yearBetween = ChronoUnit.YEARS.between(specifiedDate, currentDate);
            if (yearBetween >= 1) {
                System.out.println("图书 " + book.getTitle() + " 已经上架超过一年，是否移除？（yes/no）：");
                scanner.nextLine();//吞掉 输入选择操作 10 后的 换行符
                String response = scanner.nextLine();
                if (response.equalsIgnoreCase("yes")) {
                    removeBook(book.getBookID());
                    System.out.println("图书 " + book.getTitle() + " 已移除！");
                    i--;//因为后面的书已经向前移动，所以要重新检查当前索引位置
                }
                flg = true;
            }
        }
        if (!flg) {
            System.out.println("没有上架超过一年的图书！");
        }
    }

    public void borrowBook(int bookid) {
        loadAllbook();
        Book book = searchBookByID(bookid);
        book.setBorrowed(true);
        book.incrementBorrowedCount();
        int index = searchIndexByID(bookid);
        books[index] = book;
        storeBook();
    }

    public void returnBook(int bookId) {
        loadAllbook();
        Book book = searchBookByID(bookId);
        book.setBorrowed(false);
        int index = searchIndexByID(bookId);
        books[index] = book;
        storeBook();
    }
}
